package com.cary.demo

import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log.d
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.cary.demo.ui.theme.TestDemoTheme
import kotlinx.coroutines.delay
import androidx.compose.foundation.clickable
import androidx.compose.material3.Button
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    private lateinit var swipeCompleteReceiver: BroadcastReceiver

    companion object {
        fun isAccessibilityServiceEnabled(context: android.content.Context): Boolean {
            return try {
                val enabledServices = Settings.Secure.getString(
                    context.contentResolver,
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
                )
             //   d(TAG, "CCCC Enabled services: $enabledServices")

                if (enabledServices.isNullOrEmpty()) {
                    // 尝试备用方法
                    return checkAccessibilityServiceAlternative(context)
                }

                val expectedComponentName = ComponentName(
                    context,
                    SwipeAccessibilityService::class.java
                )

                // 更全面的匹配方式
                val fullComponentName = expectedComponentName.flattenToString()
                val packageName = context.packageName
                val serviceName = SwipeAccessibilityService::class.java.simpleName

              //  d(TAG, "CCCC Looking for service: $fullComponentName")

               val result = enabledServices.split(':').any { service ->
                 //   d(TAG, "CCCC Service: $service")
                    service.contains(packageName) && service.contains(serviceName)
                }
                d(TAG, "CCCC Service enabled: $result")
                return result
            } catch (e: Exception) {
                d(TAG, "CCCC Exception when checking accessibility service: ${e.message}")
                false
            }
        }
        private fun checkAccessibilityServiceAlternative(context: android.content.Context): Boolean {
            // 备用检查方法 - 直接跳转到设置页面让用户确认
            return false // 默认返回false，强制用户去设置页面确认
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TestDemoTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "抖音",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
        // 注册滑动完成广播接收器
        swipeCompleteReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == SwipeAccessibilityService.ACTION_SWIPE_COMPLETED) {
                    d(TAG, "收到滑动完成通知")
                    // 可以在这里处理滑动完成后的逻辑
                    isRunning = true
                }
            }
        }

        val filter = IntentFilter(SwipeAccessibilityService.ACTION_SWIPE_COMPLETED)
        registerReceiver(swipeCompleteReceiver, filter, Context.RECEIVER_NOT_EXPORTED)

    }
    override fun onDestroy() {
        super.onDestroy()
        // 注销广播接收器
        unregisterReceiver(swipeCompleteReceiver)
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    var executionCount by remember { mutableStateOf(0) }
    LaunchedEffect(executionCount) {
        d(TAG, "开始执行上划操作: $executionCount,isRunning=$isRunning")
        if (isRunning) {
            val isOpen = MainActivity.isAccessibilityServiceEnabled(context)
            d(TAG, "无障碍服务启用状态 isOpen: $isOpen")
            // 检查并调用无障碍服务
            if (isOpen) {
                delay(2000)
                // 这里需要通过某种方式获取 SwipeAccessibilityService 实例
                // 可以使用广播、绑定服务等方式
                d(TAG, "start 调用无障碍服务")
                val intent = Intent(SwipeAccessibilityService.ACTION_PERFORM_SWIPE).apply {
                    setPackage(context.packageName) // 限制只在本应用内发送
                }
                context.sendBroadcast(intent)
                executionCount++ // 增加计数器触发执行
                d(TAG, "次数 $executionCount 调用无障碍服务 success")
            } else {
                d(TAG, "无障碍服务未启用")
                Toast.makeText(context, "请先启用无障碍服务", Toast.LENGTH_LONG).show()
                // 引导用户开启无障碍服务
                val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                context.startActivity(intent)
            }
            // 添加适当的延迟避免过于频繁的执行
            val randomDelay = (10000..30000).random().toLong()
            d(TAG, "下次执行间隔: $randomDelay")
            Thread.sleep(randomDelay) // 每次执行间隔0-30秒随机
           // isRunning = false
        }
    }
    Button(
        onClick = {
            // 创建打开抖音极速版的Intent
            val intent = Intent(Intent.ACTION_VIEW).apply {
                //  data = Uri.parse("snssdk1128://") // 抖音的scheme
                data = Uri.parse("snssdk2329://") // 抖音极速版的scheme
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            try {
                context.startActivity(intent)
                Thread.sleep(1000)
                isRunning = true
                executionCount++
            } catch (e: Exception) {
                // 如果抖音极速版未安装，尝试跳转到应用商店
                Toast.makeText(context, "请先安装抖音极速版", Toast.LENGTH_SHORT).show()
                try {
                    val marketIntent = Intent(Intent.ACTION_VIEW).apply {
                        data = Uri.parse("market://details?id=com.ss.android.ugc.aweme.lite")
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                    context.startActivity(marketIntent)
                } catch (ex: Exception) {
                    Toast.makeText(context, "无法打开应用商店", Toast.LENGTH_SHORT).show()
                }
            }
        },
        modifier = modifier
    ) {
        Text(text = "打开 $name",
            fontSize = 20.sp,
            color = androidx.compose.ui.graphics.Color.White)
    }

}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TestDemoTheme {
        Greeting("Android")
    }
}
var isRunning = false
private const val TAG = "CCCC MainActivity"
